package com.yootk.test.hc;

import org.apache.hc.client5.http.classic.methods.HttpGet;
import org.apache.hc.client5.http.impl.classic.CloseableHttpClient;
import org.apache.hc.client5.http.impl.classic.CloseableHttpResponse;
import org.apache.hc.client5.http.impl.classic.HttpClients;
import org.apache.hc.core5.http.Header;
import org.apache.hc.core5.http.io.entity.EntityUtils;

/**
 * HttpClient基本使用
 */
public class HttpClientGetDemo {

    public static void main(String[] args) throws Exception {
        String requestUrl = "http://localhost/echo.action?msg=www.yootk.com"; // 请求路径
        // 1、创建一个可以被关闭的HttpClient对象
        CloseableHttpClient httpClient = HttpClients.createDefault();
        // 2、创建一个指定的请求模式，本次为GET模式
        HttpGet httpGet = new HttpGet(requestUrl); // 以GET模式发送HTTP请求
        // 3、进行HTTP请求的发送，请求发送之后一定会存在有响应信息
        CloseableHttpResponse response = httpClient.execute(httpGet); // 发送HTTP请求
        // 4、HTTP响应是分为两个部分：数据部分、头信息
        System.out.println("【获取响应数据】" + EntityUtils.toString(response.getEntity()));
        // 5、获取全部的头信息数据
        Header headers [] = response.getHeaders(); // 全部头信息
        for (Header header : headers) {
            System.out.println("\t|- 【头信息】name = " + header.getName() + "、value = " + header.getValue());
        }
        System.out.println("【HTTP状态码】" + response.getCode());
    }
}
